﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;

namespace Bing.Studio
{
    public class DatabaseTest : IDisposable
    {
        private DbConnection _dbConnection;

        public string ConnectionString { get; private set; }
        public string ProviderName { get; private set; }

        public DatabaseTest(string strConnectionString, string strProviderName)
        {
            ConnectionString = strConnectionString;
            ProviderName = strProviderName;
            _dbConnection = DbProviderFactories.GetFactory(ProviderName).CreateConnection();
            _dbConnection.ConnectionString = strConnectionString;
        }

        public Boolean Test(out Exception outError)
        {
            outError = null;
            try
            {
                _dbConnection.Open();
                _dbConnection.Close();
                return true;
            }
            catch (Exception ex)
            {
                outError = ex;
                return false;
            }
        }

        public string GetServerName()
        {
            return _dbConnection.DataSource;
        }

        public string GetDatabaseName()
        {
            return _dbConnection.Database;
        }

        public void Dispose()
        {
            if (_dbConnection.State != System.Data.ConnectionState.Closed)
            {
                _dbConnection.Close();
            }
            _dbConnection.Dispose();
        }
    }
}
